import Vue from 'vue'
import VueRouter from 'vue-router'
import state from '@/store/index'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/',
    name: 'layout',
    component: () => import('@/views/layout/Layout.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'homePage',
        component: () => import('@/views/layout/pages/home.vue')
      },
      {
        path: '/user',
        name: 'userPage',
        component: () => import('@/views/layout/pages/user.vue')
      },
      {
        path: '/forum',
        name: 'forumPage',
        component: () => import('@/views/layout/pages/forum.vue')
      },
      {
        path: '/workbench',
        name: 'workbenchPage',
        component: () => import('@/views/layout/pages/workbench.vue')
      }
    ]
  },
  {
    path: '/*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue')
  }
]
// 权限页面
const authUrls = ['/home', '/user', '/forum', '/tool']
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  if (!authUrls.includes(to.path)) {
    // 非权限页面直接放行
    next()
    return
  }
  // 是权限页面判断有无token
  if (state.getters.token) {
    next()
  } else {
    // 没有token 先去登录
    next('/login')
  }
})

export default router
